import React, { Component } from "react";
import store from "../../redux/store";
import {
    createIncrementAction,
    createDecrementAction,
    createIncrementAsyncAction,
} from "../../redux/count_action";

export default class Count extends Component {
    componentDidMount() {
        /**
         * 由于redux不会重新渲染组件，需要使用subscribe方法手动渲染
         * 注意这里直接调用render()方法是不行的，不会重新渲染
         *
         * store.subscribe()方法在每个action被dispatch了之后触发，它不能保证触发时state的值一定会被变更
         *
         * 每个组件都写这个钩子函数比较复杂，也可以直接在程序入口index.js中直接重新render整个App，但是会有效率问题
         */
        store.subscribe(() => {
            this.setState({});
        });
    }

    increment = () => {
        const number = parseInt(this.selectNumber.value);

        store.dispatch(createIncrementAction(number));
    };

    decrement = () => {
        const number = parseInt(this.selectNumber.value);

        store.dispatch(createDecrementAction(number));
    };

    incrementIfOdd = () => {
        const count = store.getState();
        if (count % 2 === 1) {
            const number = parseInt(this.selectNumber.value);

            store.dispatch(createIncrementAction(number));
        }
    };

    incrementAsync = () => {
        const number = parseInt(this.selectNumber.value);

        // setTimeout(() => {
        store.dispatch(createIncrementAsyncAction(number, 500));
        // }, 500);
    };

    render() {
        const count = store.getState();

        return (
            <div>
                <h2>当前求和为：{count}</h2>
                <select ref={(c) => (this.selectNumber = c)}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                &nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOdd}>
                    当前求和为奇数时相加
                </button>
                &nbsp;
                <button onClick={this.incrementAsync}>异步加</button>
            </div>
        );
    }
}
